<?php if(!defined('PUBLIC_DIR')) die('No Access!');
using('System');
using('System.Data');
using('System.Web.MVC');

Cnamespace('System.Web.MVC');
class Route implements iRoute{
	private static $DBHandler = NULL;
	private $Name;
	private $Uri;
	private $Action;
	private $Params = array();

	public function __construct($_name, Uri $_uri = null, Action $_action = null, $_additionalParameters = array()){
		if(!is_null($_uri) && is_a($_uri, 'Uri') && !is_null($_action) && is_a($_action, 'Action')){
			$this->Name = $_name;
			$this->Uri = $_uri;
			$this->Action = $_action;
		}else{
			if (self::$DBHandler == NULL)
				self::$DBHandler = Config::GetProvider();
			self::$DBHandler->Query("SELECT pattern, conditions, action, additionalParameters FROM [Routes] WHERE name = '$_name' LIMIT 1;");
			$trace = self::$DBHandler->FetchArray();
			$this->Name = $_name;
			$this->Uri = new Uri($_name, $trace['pattern'], (array)unserialize($trace['conditions']));
			$this->Action = new Action($trace['action']);
		}
	}
	public function GetAction(){
		return $this->Action;
	}
	public function GetParams(){
		return $this->Params;
	}
	public function Match($_referer){
		//Extract URL params
		preg_match_all('@:([\w]+)@', $this->Uri->getPattern(), $paramNames, PREG_PATTERN_ORDER);
		$paramNames = $paramNames[0];

		//Convert URL params into regex patterns, construct a regex for this route
		$patternAsRegex = $this->Uri->CreateRegex();

		//Cache URL params' names and values if this route matches the current HTTP request
		if(preg_match($patternAsRegex, $_referer, $paramValues)){
			array_shift($paramValues);
			foreach($paramNames as $index => $value){
				if(isset($paramValues[substr($value, 1)])){
					$this->params[substr($value, 1)] = urldecode($paramValues[substr($value, 1)]);
				}
			}
			return True;
		}
		return False;
	}
}
